package com.kaishengit.web;


import java.io.IOException;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kaiashengit.service.UserService;
import com.kaisengit.enity.User;


public class UserServlet extends HttpServlet {
	
	
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
			
		String task = request.getParameter("task");
		
		String method = request.getMethod();
		
		if("login".equals(task)){
			
			if("GET".equals(method)){
				
				tologin(request,response);
				
			}else if("POST".equals(method)){
				
				login(request,response);
			}
		}

}


	



private void login(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		
	String name = request.getParameter("username");
	String pwd = request.getParameter("userpwd");
	
	UserService userservice = new UserService();
	User user = userservice.find(name,pwd);
	if(user == null){
		response.sendRedirect("user.jspx?error=001");
	}else {
		
		if("worker".equals(user.getRole())){
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			request.getRequestDispatcher("/WEB-INF/views/add.jsp").forward(request, response);
			
		}else if("admin".equalsIgnoreCase(user.getRole())){
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			
			//request.getRequestDispatcher("sales.jspx?task=list").forward(request, response);
			response.sendRedirect("sales.jspx?task=list");
		}
			
		
		
	}
	
	

}

private void tologin(HttpServletRequest request,
	HttpServletResponse response)throws ServletException, IOException {
	
	request.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(request, response);

}


}
